import { View, Image, Text, ScrollView } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { Tabs, Button, Popup } from '@nutui/nutui-react-taro';
import { useState, useEffect, useMemo, useRef } from 'react';
import { InputSearch, InfiniteList, Filter, TagChecker } from '@/components';
import type { ActionType } from '@/components/InfiniteList';
import { useRequest } from '@/hooks';
import { BasicLayout } from '@/layouts';
import { getApiChoiceOutDressListCompanyId, getApiChoiceOutGet } from '@/api';
import { ProductType, productTypeMap } from '@/constants/product';
import type { GetApiTypeGetResponse, GetApiChoiceOutDressListCompanyIdResponse } from '@/api';
import styles from './index.module.scss';
import { StorageKey } from '@/constants/storage';
import { RouterUtil, TabbarUtil } from '@/utils';
import { usePreselectStore } from '@/models';
import { useDidShow } from '@tarojs/taro';

type FilterOption = GetApiTypeGetResponse[0];
type DressItem = NonNullable<GetApiChoiceOutDressListCompanyIdResponse['data']>[0];

interface QueryParams {
  queryName?: string;
  dressType?: number;
  queryInfo?: string;
}

const Dress = () => {
  const [searchValue, setSearchValue] = useState<string>('');
  const [activeTab, setActiveTab] = useState<number>(0);
  const [filterOptions, setFilterOptions] = useState<FilterOption[]>([]);
  const [filterValues, setFilterValues] = useState<Record<string, any>>({});
  const [showMoreFilters, setShowMoreFilters] = useState<boolean>(false);
  const [tempMoreFilterValues, setTempMoreFilterValues] = useState<Record<string, any>>({});
  const [queryParams, setQueryParams] = useState<QueryParams>({
    dressType: ProductType['婚纱'], // 默认婚纱
  });

  const infiniteListRef = useRef<ActionType>(null);
  const { dresses, persons } = usePreselectStore();

  // 获取公司ID（从路由参数或其他地方获取）
  const shopId = Taro.getStorageSync(StorageKey.SHOP_ID);

  // 页面显示时更新 tabbar badge
  useDidShow(() => {
    const totalCount = dresses.length + persons.length;
    TabbarUtil.setPreselectBadge(totalCount);
  });

  // 服装类型选项
  const dressTypeOptions = useMemo(() => {
    return Array.from(productTypeMap.entries()).map(([value, item]) => ({
      title: item.text,
      value,
    }));
  }, []);

  // 构建筛选字段配置（只显示前4个）
  const filterFields = useMemo(() => {
    return filterOptions
      ?.filter((option) => option.filed && option.key) // 过滤掉没有 filed 或 key 的选项
      ?.slice(0, 4)
      .map((option, index) => {
        const key = option.key || `filter-key-${index}`; // 确保 key 有值
        const name = option.filed || option.key || key; // 确保 name 有值
        return {
          name,
          title: option.filed || option.key || name,
          key, // 确保 key 不为空
          options: (option.value || []).map((val) => ({ text: val, value: val })),
        };
      }) || [];
  }, [filterOptions]);


  // 剩余的筛选字段（第5个及以后）
  const moreFilterOptions = useMemo(() => {
    if (filterOptions?.length <= 4) return [];
    return filterOptions
      .filter((option) => option.filed && option.key) // 过滤掉没有 filed 或 key 的选项
      .slice(4)
      .map((option, index) => {
        const key = option.key || `more-filter-key-${index}`; // 确保 key 有值
        const name = option.filed || option.key || key; // 确保 name 有值
        return {
          name,
          title: option.filed || option.key || name,
          key, // 确保 key 不为空
          options: (option.value || []).map((val) => ({ text: val, value: val })),
        };
      });
  }, [filterOptions]);

  // 获取筛选条件
  const {
    run: fetchFilterOptions,
  } = useRequest(
    getApiChoiceOutGet,
    {
      manual: true,
      onSuccess: (data) => {
        setFilterOptions(data || []);
      },
    }
  );

  // 获取筛选条件
  useEffect(() => {
    if (queryParams.dressType) {
      const dressTypeText = productTypeMap.get(queryParams.dressType)?.text;
      if (dressTypeText) {
        fetchFilterOptions({
          airyType: dressTypeText,
        });
      }
    }
  }, [queryParams.dressType]);

  // 处理搜索
  const handleSearch = () => {
    infiniteListRef.current?.refresh();
  };

  // 构建查询条件字符串（使用 useMemo 缓存结果，避免不必要的重新计算）
  const queryInfo = useMemo(() => {
    const queryInfoArray: string[] = [];
    Object.entries(filterValues).forEach(([, value]) => {
      if (value && value !== 'ignore') {
        if (Array.isArray(value)) {
          queryInfoArray.push(value.join(','));
        } else {
          queryInfoArray.push(value);
        }
      }
    });
    return queryInfoArray.length > 0 ? queryInfoArray.join(',') : undefined;
  }, [filterValues]);

  // 处理Tab切换
  const handleTabChange = (index: number) => {
    setActiveTab(index);
    const selectedType = dressTypeOptions[index]?.value;
    if (selectedType) {
      setQueryParams(prev => ({
        ...prev,
        dressType: selectedType,
      }));
      // 清空筛选条件
      setFilterValues({});
      setTempMoreFilterValues({});
      setShowMoreFilters(false);
    }
  };

  // 处理筛选条件变化
  const handleFilterChange = (values: Record<string, any>) => {
    setFilterValues(values);
  };

  // 处理更多筛选条件变化（只更新临时状态）
  const handleMoreFilterChange = (fieldKey: string, values: string[]) => {
    setTempMoreFilterValues(prev => ({
      ...prev,
      [fieldKey]: values,
    }));
  };


  // 应用筛选（将临时状态合并到正式状态并调用接口）
  const applyMoreFilters = () => {
    const newFilterValues = {
      ...filterValues,
      ...tempMoreFilterValues,
    };
    setFilterValues(newFilterValues);
    setShowMoreFilters(false);
  };

  // 重置筛选（只重置临时状态）
  const resetMoreFilters = () => {
    setTempMoreFilterValues({});
    setFilterValues({});
    setShowMoreFilters(false);
  };


  // 构建请求参数（使用稳定的依赖项，确保引用稳定）
  const requestParams = useMemo(() => {
    return {
      companyId: shopId,
      ...queryParams,
      queryName: searchValue || undefined,
      queryInfo,
    };
  }, [shopId, queryParams, searchValue, queryInfo]);

  // 渲染服装项目（每一项显示两个服装）
  const renderDressRow = (rowData: DressItem[]) => {
    return (
      <View className={styles.dressRow}>
        {rowData.map((item, index) => (
          <View key={item?.id || `empty-${index}`} className={styles.dressItem}>
            {item ? (
              <View onClick={() => {
                RouterUtil.navigateTo('/pages/dress/detail/index', {
                  id: item.id,
                  type: queryParams.dressType,
                });
              }}>
                <View className={styles.dressImage}>
                  {item.shortUrl ? (
                    <Image
                      src={item.shortUrl}
                      mode="aspectFill"
                      className={styles.image}
                    />
                  ) : (
                    <View className={styles.placeholder}>暂无图片</View>
                  )}
                </View>
                <View className={styles.dressInfo}>
                  <Text className={styles.dressName}>{item.dressName}</Text>
                  <Text className={styles.dressPrice}>
                    ¥{item.maxRentPrice || 0}
                  </Text>
                  {item.sizeName && (
                    <Text className={styles.dressSize}>尺码: {item.sizeName}</Text>
                  )}
                </View>
              </View>
            ) : (
              // 空占位符，保持布局一致性
              <View className={styles.emptyPlaceholder} />
            )}
          </View>
        ))}
      </View>
    );
  };

  // 将服装列表数据转换为每行两个的格式
  const formatDressData = (data: DressItem[]) => {
    const rows: DressItem[][] = [];
    for (let i = 0; i < data.length; i += 2) {
      const row = [data[i]];
      if (data[i + 1]) {
        row.push(data[i + 1]);
      }
      rows.push(row);
    }
    return rows;
  };

  // 请求函数包装器
  const requestWrapper = async (params: any) => {
    const response = await getApiChoiceOutDressListCompanyId({
      ...requestParams,
      pageNum: params.pageNum,
      pageSize: params.pageSize,
    });
    
    // 将数据转换为行格式
    const formattedData = formatDressData(response.data?.data || []);
    
    // 计算行总数：原始总数除以2，向上取整
    const originalTotal = response.data?.total || 0;
    const rowTotal = Math.ceil(originalTotal / 2);
    
    return {
      ...response,
      data: {
        data: formattedData,
        current: response.data?.current || 1,
        pageSize: response.data?.pageSize || 10,
        total: rowTotal,
      },
    };
  };

  return (
    <BasicLayout 
      title={<View className={styles.searchSection}>
        <InputSearch
          value={searchValue}
          placeholder="搜索服装名称"
          onChange={(value) => setSearchValue(value || '')}
          onSearch={handleSearch}
        />
      </View>} 
      className={styles.page}
      fill
      safeArea={false}
    >
      <View className={styles.dressPage}>
        {/* Tabs */}
        <View className={styles.tabsSection}>
          <Tabs
            value={activeTab}
            onChange={handleTabChange}
            direction="horizontal"
          >
            {dressTypeOptions.map((option) => (
              <Tabs.TabPane key={option.value} title={option.title} />
            ))}
          </Tabs>
        </View>

        {/* 筛选组件 */}
        <View className={styles.filterSection}>
          <Filter
            className={styles.mainFilter}
            fields={filterFields}
            value={filterValues}
            onChange={handleFilterChange}
            style={moreFilterOptions.length > 0 ? { paddingRight: '68px' } : { paddingRight: 0 }}
          />
          {moreFilterOptions.length > 0 && (
            <Button
              className={styles.moreFilterBtn}
              size="small"
              fill="outline"
              onClick={() => {
                // 打开弹窗时，初始化临时状态为当前筛选值
                const currentMoreFilterValues: Record<string, any> = {};
                moreFilterOptions.forEach(option => {
                  if (option.name && filterValues[option.name]) {
                    currentMoreFilterValues[option.name] = filterValues[option.name];
                  }
                });
                setTempMoreFilterValues(currentMoreFilterValues);
                setShowMoreFilters(true);
              }}
            >
              筛选
            </Button>
          )}
        </View>

        {/* 服装列表 */}
        <InfiniteList
          className={styles.dressListContainer}
          params={requestParams}
          request={requestWrapper}
          renderItem={renderDressRow}
          actionRef={infiniteListRef}
          refresherEnabled
          padding
        />

        {/* 更多筛选弹窗 */}
        <Popup
          visible={showMoreFilters}
          position="bottom"
          title="筛选条件"
          closeable
          onClose={() => setShowMoreFilters(false)}
          className={styles.moreFilterPopup}
        >
          <ScrollView scrollY className={styles.moreFilterContent}>
            {moreFilterOptions.map((option) => (
              <View key={option.key || option.name} className={styles.filterGroup}>
                <Text className={styles.filterTitle}>{option.title}</Text>
                <TagChecker
                  options={(option.options || [])}
                  value={tempMoreFilterValues[option.name || ''] || []}
                  onChange={(values) => handleMoreFilterChange(option.name || '', values as string[])}
                />
              </View>
            ))}
          </ScrollView>
          
          <View className={styles.moreFilterActions}>
            <Button
              size="large"
              fill="outline"
              onClick={resetMoreFilters}
              className={styles.resetBtn}
            >
              重置
            </Button>
            <Button
              size="large"
              type="primary"
              onClick={applyMoreFilters}
              className={styles.applyBtn}
            >
              确定
            </Button>
          </View>
        </Popup>

      </View>
    </BasicLayout>
  );
};

export default Dress;
